40923235 cp2020

  • Home
    • Site Map
    • reveal
    • blog
  • 首頁
  • HW1
    • UNIT 1
      • Strategies for Learning學習策略
      • What You Need to Know About the Course您需要了解的課程內容
      • About these Materials 關於這些材料
      • Metacognition元認知
      • Metacognition in Action行動中的元認知
    • UNIT2
      • Introduction簡介
      • Functions of Computers  Input  Output  Storage  and Processing計算機功能  輸入  輸出  存儲和處理
      • Hardware硬件
      • Software軟件
      • Fireware固件
      • Componentization  Standardization組件化  標準化
      • Connection Interfaces and Cables連接接口和電纜
  • HW2
  • HW3
    • Chacrater input字符輸入
      • input strings types int輸入字符串類型int
      • Discussion討論區-1
      • User input in Python使用Python的用戶輸入
      • Manipulating strings a few ways處理字符串幾種方法
    • Odd Or Even奇數或偶數
      • Exercise 2 and solution練習2和解決方案
      • Discussion討論區-2
      • Modular arithmetic the modulus operator模塊化算術模運算符
      • Conditionals有條件的
      • Checking for equality and comparators in general檢查是否相等以及一般的比較器
    • List Less Than Ten列出少於十
      • Exercise 3 and Solution練習3和解決方案
      • Discussion討論區-3
      • Lists清單
      • More Conditionals更多條件
  • 心得
Lists清單 << Previous Next >> 心得

More Conditionals更多條件

The nice thing about conditionals is that they follow logical operations. They can also be used to test equality. Let’s do a small example. Let’s say I want to make a piece of code that converts from a numerical grade (1-100) to a letter grade (A, B, C, D, F). The code would look like this:

grade = input("Enter your grade: ")
if grade >= 90:
  print("A")
elif grade >= 80:
  print("B")
elif grade >= 70:
  print("C")
elif grade >= 65:
  print("D")
else:
  print("F")

What happens if grade is 50? All the conditions are false, so "F" gets printed on the screen. But what if grade is 95? Then all the conditions are true and everything gets printed, right? Nope! What happens is the program goes line by line. The first condition (grade >= 90) is satisfied, so the program enters into the code inside the if statement, executing print("A"). Once code inside a conditional has been executed, the rest of the conditions are skipped and none of the other conditionals are checked.

關於條件的好處是它們遵循邏輯運算。它們也可以用於測試相等性。讓我們做一個小例子。假設我要編寫一段代碼,將其從數字等級(1-100)轉換為字母等級(A,B,C,D,F)。代碼如下所示:

grade = input("Enter your grade: ")
if grade >= 90:
  print("A")
elif grade >= 80:
  print("B")
elif grade >= 70:
  print("C")
elif grade >= 65:
  print("D")
else:
  print("F")

如果grade是50,會發生什麼?所有條件均為假,因此"F"將其打印在屏幕上。但是,如果grade是95,該怎麼辦?然後所有條件都成立,一切都打印出來了,對吧?不!程序將逐行執行。滿足第一個條件(等級> = 90),因此程序將輸入if語句內的代碼,執行print("A")。一旦執行了條件語句中的代碼,將跳過其餘條件,並且不檢查其他條件。


Lists清單 << Previous Next >> 心得

Copyright © All rights reserved | This template is made with by Colorlib